package com.mt.fpb.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mt.fpb.mapper.WxProductMapper;
import com.mt.fpb.mapper.WxProductOrderMapper;
import com.mt.fpb.model.RxEmployee;
import com.mt.fpb.model.WxProductOrder;
import com.mt.fpb.model.vo.CommonResult;
import com.mt.fpb.utils.ParseXml;
import com.vbao.service.trade.VbaoChargeSystemHandler;
import com.vbao.service.trade.bean.request.OneQRCodePaymentRequest;
import com.vbao.service.trade.bean.request.TradeRequestXml;
import com.vbao.service.trade.utils.Base64;
import com.vbao.service.trade.utils.TradeCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * FileName: YeepCreatorderController
 * Author:   wang
 * Date:     2021/8/17 16:19
 */
@RestController
@RequestMapping("pay")
public class VbaoCreatorderController {

    @Autowired
    private WxProductOrderMapper productOrderMapper;

    @Autowired
    private WxProductMapper wxProductMapper;

    //支付状态已支付
    private final static int PAID = 1;

    private Map map;
//HttpSession session
    @PostMapping("getpay")
    public CommonResult get(String employeeId,String productName,String productId,String id,float orderAmount, HttpSession session) throws ServletException, IOException {
        /** 1.字符集UTF-8 固定值不变 */
        String InputCharset = "UTF-8";
        /** 2.微保分配的商户号(生产会变) */
        //String customerNo = "202108240001";//测试值
        String customerNo = "202108240002";
        /** 3.微保分配的商户密钥(生产会变) */
        //String key = "LgG9TWEY1r5ezE8KdSmz";//测试号
        String key = "n7hPATGKB6aQRfmncrCV";
        /** 5.商户的商品代码(生产会变) */
        String goodNo = "ONEQRCODE";
        /** 6.访问服务地址(生产会变) */
        //String requestMobilePayXmlurl = "http://120.27.167.200:8080/vbaoPay/cust/payService/GetOneQRCode";//测试
        String requestMobilePayXmlurl = "http://pay.chinavbao.com/vbaoPay/cust/payService/GetOneQRCode";

        /**   在进行第7步之前，进行个人额度的校验
        个人额度校验规则：在支付时将减去在订单表中该单位在订单中已经支付过的pay_money总和
         当orderAmount大于此金额时将要提示：超过个人最高限额，请修改买入金额*/
        if ("fail".equals(islimit(employeeId, orderAmount, productId))) {
            return CommonResult.fail(500, "超过个人最高限额，请修改买入金额");
        }

        VbaoChargeSystemHandler vbaoChargeSystemHandler = new VbaoChargeSystemHandler();
        /** 7.发送报文信息 */
        OneQRCodePaymentRequest oneQRCodeRequest = new OneQRCodePaymentRequest();
        oneQRCodeRequest.setVersion("6.0");
        oneQRCodeRequest.setCustomerNo(customerNo);
        oneQRCodeRequest.setGoodNo(goodNo);
        //设置订单号
        //oneQRCodeRequest.setOrderNo("YMF" + System.nanoTime());
        oneQRCodeRequest.setOrderNo(id);
        //设置交易金额
        oneQRCodeRequest.setOrderAmount(String.valueOf(orderAmount));
        //oneQRCodeRequest.setProductName("优享宝-90"); 设置产品名称
        oneQRCodeRequest.setProductName(productName);
        oneQRCodeRequest.setProductDesc("定制");
        oneQRCodeRequest.setNotifyUrl("http://money.confidant.top/getVbao/get");
        //设置产品id
        oneQRCodeRequest.setExt1(productId);
        //oneQRCodeRequest.setPostBackUrl("http://money.confidant.top/login");
        oneQRCodeRequest.setExt2(productName);
        // 组装发送报文
        TradeRequestXml tradeRequestXml = vbaoChargeSystemHandler
                .creatRequestXml(oneQRCodeRequest, key, InputCharset,
                        TradeCodeEnum.ONEQRCOCE_PAY.getCode());
        System.out.println("发送明文报文:" + tradeRequestXml.getOriRequestXml());
        System.out.println("发送密文报文:" + tradeRequestXml.getRequestXml());

        System.out.println("发送报文:" + tradeRequestXml.getRequestXml());
        if (tradeRequestXml.getErrMsg() == null) {
            // 获取返回报文
            String returnDKPayxml = vbaoChargeSystemHandler.http(
                    requestMobilePayXmlurl, tradeRequestXml.getRequestXml(),
                    InputCharset);
            System.out.println("返回密文报文" + returnDKPayxml);
            if (null != returnDKPayxml && returnDKPayxml.length() > 0) {
                String returnOriDKPayxml = "";// 返回明文报文
                try {
                    // 进行解密
                    returnOriDKPayxml = Base64.decode(returnDKPayxml,
                            InputCharset);
                    System.out.println("解密后报文" + returnOriDKPayxml);
                    // 进行验签
                    if (null != returnOriDKPayxml
                            && returnOriDKPayxml.length() > 0) {
                        boolean flag = vbaoChargeSystemHandler.verifySignature(
                                returnOriDKPayxml, key, InputCharset);
                        if (flag) {
                            System.out.println("验签正确");
                            // 汉字的解码
                            System.out.println(URLDecoder.decode(
                                    returnOriDKPayxml, InputCharset));
                            String xml = URLDecoder.decode(returnOriDKPayxml, InputCharset);
                            map = ParseXml.parseXml(xml);
                            System.out.println("codeUrl:"+ map.get("CodeUrl"));
                            session.setAttribute("id",id);
                            System.out.println("id:"+session.getAttribute("id"));
                        }
                    }
                } catch (UnsupportedEncodingException e) {
                    System.out.println("解析密文报文有误:" + e.getMessage());
                }
            }
        } else {
            System.out.println(tradeRequestXml.getErrMsg());
        }
        return CommonResult.success(map);

    }

    private String islimit(String employeeId, float orderAmount, String productId) {
        System.out.println("开始进入个人额度计算");
        float totalPayMoney = 0.0f;
        QueryWrapper<WxProductOrder> query = new QueryWrapper<WxProductOrder>();
        query.eq("employee_id", employeeId);
        query.eq("order_status", PAID);
        query.eq("product_id", productId);
        List<WxProductOrder> wxProductOrders = productOrderMapper.selectList(query);
        for(WxProductOrder wpo : wxProductOrders) {
            totalPayMoney += wpo.getPayMoney();
        }
        //查询当前产品个人限额

        float totalQyota =wxProductMapper.findProductMaximumLimit(productId);
        if (totalQyota - totalPayMoney - orderAmount < 0) {
            System.out.println("超过剩余个人额度");
            return "fail";
        }
        System.out.println("个人额度充裕");
        return "success";
    }
}
